/* ************************************************************************
> File Name:     5.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年05月03日 星期二 22时43分53秒
> Description:   
 ************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100

typedef struct node *link;
struct node{
    char s[N];
    link next;
};

struct node sential = {
    {'\0'}, &sential
};

link head = &sential;

link make_node(char *s)
{
    link p = malloc(sizeof *p);
    strncpy(p->s, s, N);
    p->next = NULL;
}

void free_node(link p)
{
    free(p);
    p = NULL;
}

int timecmp(char *s1, char *s2)
{
    char *p1 = strrchr(s1, ' '); 
    char *p2 = strrchr(s2, ' '); 
    ++p1;
    ++p2;
    if (strcmp(p1, p2) < 0){
        return 1;
    }

    return 0;
}

void order_insert(link p)
{
    if (head->next == head){
        head->next = p;
        p->next = head;
    }
    else{
        link q = head->next;
        link pre = head;
        while (q != head && timecmp(q->s, p->s)){
            pre = q;
            q = q->next;
        }
        pre->next = p;
        p->next = q;
    }
}

int main(int argc, char *argv[])
{
    char *src = argv[1];
    FILE *f;

    if (!(f = fopen(src, "r+"))){
        perror(src);
    }

    char s[N];
    while (fgets(s, N, f)){
        link p = make_node(s);
        order_insert(p);
    }

    rewind(f);

    link p = head->next;
    int i = 1;
    while (p != head){
        strncpy(s, p->s, N);
        s[0] = i + '0';
        ++i;
        fputs(s, f);
        p = p->next;
    }

    fclose(f);

    return 0;
}
